package com.reservationserver.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.reservationpojo.entity.Badminton;
import com.reservationpojo.sendmessageevent.Sse;
import com.reservationpojo.utils.Result;
import com.reservationserver.mapper.user.UserBadmintonMapper;
import com.reservationserver.service.user.UserBadmintonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/userbadminton")
@RestController
@RequiredArgsConstructor
@Tag(name = "用户羽毛球")
public class UserbadmintonController {

    private final UserBadmintonService badmintonService;

    private final UserBadmintonMapper badmintonMapper;

    private final RedisTemplate redisTemplate;
    /**
     *预约位置，传递预约时间，位置，学号
     * 前端在此方法执行完成之后进行查看预约记录的访问
     * @param badminton 预约时间 位置 学号
     * @return 二维码
     * ce
     */
    @Operation(summary = "预约")
    @PostMapping("/reservation")
    public Result reservePosition(@RequestBody Badminton badminton)throws IOException{
        log.info("发送预约信息：{}",badminton);
        if(!LocalDateTime.now().isBefore(badminton.getReservationStartTime())){
            log.info("已不可预约当前时间段");
            return Result.error("已不可预约当前时间段");
        }
        List<LocalDateTime> timeList=badmintonMapper.reservationStartTimeList(badminton.getReservedByid());
        int timelen=timeList.size();
        //不允许重复预约时
        if(!badmintonMapper.isrepeeate()){
            if(timelen>0&&timeList.get(timelen-1).toLocalDate().isEqual(badminton.getReservationStartTime().toLocalDate())){
                log.info("禁止重复预约");
                return Result.error("禁止重复预约");
            }
        }
//        if (badmintonMapper.isBlack(badminton.getReservedByid())) {
//            return Result.error("您已被拉黑，请联系管理员");
//        }
        String badmintonCourt="badminton"+badminton.getPosition().charAt(0);
        //判断预约位置是否被关闭
//        if(badmintonMapper.checkShutCourt(badmintonCourt)!=null){
//            return Result.error("该位置已被关闭");
//        }
//        if(!Objects.equals(badmintonMapper.isFree(badminton),null)){
//            log.info("该位置已被预约");
//            return Result.error("该位置已被预约");
//        }
        String redisKey="badminton"+badminton.getPosition()+badminton.getReservationStartTime().toString();
        redisTemplate.opsForValue().set(redisKey,badminton.getReservedByid(),60, TimeUnit.SECONDS);
        Sse.saveEmitter("badminton"+badminton.getReservedByid());
        badmintonService.reservePosition(badminton);
        log.info("data:{}",badminton);
        return Result.success("预约成功");
    }

    /**
     * 反序列化字节数组获取二维码
     * @param createTime 预约创建时间
     * @param uid 学号
     * @return 二维码
     * @throws IOException
     *ce
     */
    @Operation(summary = "获取二维码")
    @PostMapping("/selectQrcode")
    public Result selectQrcode(String createTime,String uid)throws IOException {
        log.info("获取指定预约的，创建时间：{}，学号:{}", createTime, uid);
        log.info("jian:{}","badminton"+createTime + uid);
        String imageBase= (String) redisTemplate.opsForValue().get("badminton"+createTime + uid);
        return Result.success(imageBase);
    }
    /**
     * 根据学号查询全部的预约记录
     * 此方法在预约完成之后也调用
     * @param uid 学号
     * @return 全部预约记录
     * 测
     */
    @Operation(summary = "查询预约信息")
    @GetMapping("/checkReservation")
    public Result checkReservation(String uid,Integer page){
        log.info("查看预约信息");
        List<Badminton> checkList=badmintonService.checkReservation(uid,page);
        return Result.success(checkList);
    }
    /**
     * 删除预约
     * @param
     * @return 空
     * 测
     */
    @Operation(summary = "删除预约")
    @PostMapping("/deleteReservation")
    public Result deletereservation(@RequestBody Badminton badminton){
        log.info("取消预约：{}",badminton);
        Sse.removeEmitter("badminton"+badminton.getReservedByid());
        badmintonService.deleteReservation(badminton);
        return Result.success("已取消预约");
    }
    /**
     * 传递两个列表一个是时间段起始时间列表另一个是结束时间
     * @param starttimeList 开始时间列表
     * @return 每个时间段对应的剩余空位数量
     * 测 使用params传递
     */
    @Operation(summary = "获取对应时段空闲位置数量")
    @PostMapping("/BadmintonFreeNum")
    public Result badmintonfreenum(@RequestParam("starttimeList") List<String> starttimeList){
        log.info("获取对应时间段空余位置数量start:{},end:{}",starttimeList);
        List<Integer> messageList = new ArrayList<>();
        List<String> courtShutDown= badmintonMapper.getCourt("badminton");
        int len =courtShutDown.size();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        for (String s : starttimeList) {
            LocalDateTime stime = LocalDateTime.parse(s, formatter);
            Integer num = 28 - badmintonMapper.freePositionNum(stime) - len * 4;
            messageList.add(num);
        }
        String message = JSONObject.toJSONString(messageList);
        return Result.success(message);
    }
    /**
     * 传递开始与结束时间
     * @param starttime 一个时间段的开始时间
     * @param endtime 一个时间段的结束时间
     * 测
     */
    @Operation(summary = "空闲的位置")
    @PostMapping("/BadmintonFreePosition")
    public Result badmintonFreePosition(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime starttime,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endtime){
        log.info("通过时间查找空余位置:{},{}",starttime,endtime);
        List<String> messageList=badmintonMapper.positionSelectByTime(starttime,endtime);
        List<String> stringList = Arrays.asList("1-A","1-B","1-C","1-D","2-A","2-B","2-C","2-D","3-A","3-B","3-C","3-D","4-A","4-B","4-C","4-D","5-A","5-B","5-C","5-D","6-A","6-B","6-C","6-D","7-A","7-B","7-C","7-D");
        List<Boolean> booleanList=Arrays.asList(false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false);
        for (String s : messageList) {
            for (int i = 0; i < stringList.size(); i++) {
                if (Objects.equals(s,stringList.get(i))) {
                    booleanList.set(i, true);
                }
            }
        }

        String message = JSONObject.toJSONString(booleanList);
        log.info("01串{}",message);
        return Result.success(message);
    }
}
